﻿using suirui.ZhuMu.Model;
using suirui.ZhuMu.Log;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using suirui.ZhuMu.Entity;
using suirui.ZhuMu.Entity.Entities;
using System.Linq.Expressions;

namespace suirui.ZhuMu.Repositories
{
    /// <summary>
    /// EF 实现仓储接口
    /// </summary>
    /// <typeparam name="T">实体</typeparam>
    public class AbstractRepository<T> where T : class
    {
        private readonly mjgamesContext _Context;
        private readonly string _OperateName;

        public AbstractRepository(mjgamesContext context, string operateName)
        {
            _Context = context;
            _OperateName = operateName;
        }

        public async Task<ReturnListDto<T>> GetList<TKey>(GetParamsDto paramsDto,
            Expression<Func<T, dynamic>> select,
            Expression<Func<T, bool>> where,
            Expression<Func<T, TKey>> order,
            bool isAsc)
        {
            var listDto = new ReturnListDto<T>();
            try
            {
                var total = 0;
                var list = await QueryPage.getPageData<T, TKey>(_Context, select, where, order, paramsDto.PageIndex, paramsDto.PageSize, out total, isAsc);

                listDto.total = total;
                listDto.Data = list;
                if (list.Count > 0)
                {
                    listDto.Code = ErrorCode.Success;
                    listDto.Message = $"查询{_OperateName}列表成功！";
                }
                else
                {
                    listDto.Code = ErrorCode.Success;
                    listDto.Message = $"查询{_OperateName}列表不存在！";
                }
                listDto.pageSize = paramsDto.PageSize;
                listDto.pageNo = paramsDto.PageIndex;

                return listDto;
            }
            catch (Exception ex)
            {
                listDto.Code = ErrorCode.EFError;
                listDto.Message = "EF操作错误";
                DefaultLogFactory.Instance.Database_Loger.Error(new { title = $"查询{_OperateName}出错", param = where.ToString(), response = ex });
                return listDto;
            }
        }

        public Task<ReturnListDto<T>> GetById(Expression<Func<T, bool>> where)
        {
            var listDto = new ReturnListDto<T>();
            return Task.Run(() =>
            {
                try
                {
                    var t = _Context.Set<T>().FirstOrDefault(where);

                    listDto.total = 1;
                    listDto.Data = t == null ? new List<T>() : new List<T>() { t };
                    if (t != null)
                    {
                        listDto.Code = ErrorCode.Success;
                        listDto.Message = $"查询{_OperateName}列表成功！";
                    }
                    else
                    {
                        listDto.Code = ErrorCode.Success;
                        listDto.Message = $"查询{_OperateName}不存在！";
                    }
                    listDto.pageSize = 1;
                    listDto.pageNo = 1;
                    return listDto;
                }
                catch (Exception ex)
                {
                    listDto.Code = ErrorCode.EFError;
                    listDto.Message = "EF操作错误";
                    DefaultLogFactory.Instance.Database_Loger.Error(new { title = $"查询{_OperateName}出错", param = where.ToString(), response = ex });
                    return listDto;
                }
            });
        }

        public Task<ReturnListDto<T>> GetTById(Func<List<T>> where)
        {
            var listDto = new ReturnListDto<T>();
            return Task.Run(() =>
            {
                try
                {
                    var t = where?.Invoke();
                    //var t = _Context.Set<T>().FirstOrDefault(where);

                    listDto.total = t.Count;
                    listDto.Data = t;
                    if (t != null)
                    {
                        listDto.Code = ErrorCode.Success;
                        listDto.Message = $"查询{_OperateName}列表成功！";
                    }
                    else
                    {
                        listDto.Code = ErrorCode.SuccessEmpty;
                        listDto.Message = $"查询{_OperateName}不存在！";

                    }
                    listDto.pageSize = 1;
                    listDto.pageNo = 1;
                    return listDto;
                }
                catch (Exception ex)
                {
                    listDto.Code = ErrorCode.EFError;
                    listDto.Message = "EF操作错误";
                    DefaultLogFactory.Instance.Database_Loger.Error(new { title = $"查询{_OperateName}出错", param = where.ToString(), response = ex });
                    return listDto;
                }
            });
        }

        public IEnumerable<T> GetList()
        {
            return _Context.Set<T>().ToList();
        }

        public async Task<IEnumerable<T>> GetListAsync()
        {
            return await _Context.Set<T>().ToListAsync();
        }

        public Task<APIResult> Add(T t)
        {
            var result = new APIResult();
            return Task.Run(() =>
            {
                _Context.Set<T>().Add(t);

                if (_Context.SaveChanges() >= 0)
                {
                    result.Code = ErrorCode.Success;
                    result.Message = $"创建{_OperateName}成功";
                }
                else
                {
                    result.Code = ErrorCode.ServiceError;
                    result.Message = $"创建{_OperateName}失败";
                    DefaultLogFactory.Instance.Message_Loger.Error(new { title = $"创建{_OperateName}失败", param = t, response = result });
                }
                return result;
            });
        }

        public Task<APIResult> AddRange(List<T> t)
        {
            var result = new APIResult();
            return Task.Run(() =>
            {
                _Context.Set<T>().AddRange(t);

                if (_Context.SaveChanges() >= 0)
                {
                    result.Code = ErrorCode.Success;
                    result.Message = $"创建{_OperateName}成功";
                }
                else
                {
                    result.Code = ErrorCode.ServiceError;
                    result.Message = $"创建{_OperateName}失败";
                    DefaultLogFactory.Instance.Message_Loger.Error(new { title = $"创建{_OperateName}失败", param = t, response = result });
                }
                return result;
            });
        }

        public Task<APIResult> Update(T t)
        {
            var result = new APIResult();
            return Task.Run(() =>
            {
                _Context.Set<T>().Update(t);

                if (_Context.SaveChanges() >= 0)
                {
                    result.Code = ErrorCode.Success;
                    result.Message = $"更新{_OperateName}成功";
                }
                else
                {
                    result.Code = ErrorCode.ServiceError;
                    result.Message = $"更新{_OperateName}失败";

                    DefaultLogFactory.Instance.Message_Loger.Error(new { title = $"更新{_OperateName}失败", param = t, response = result });
                }
                return result;
            });
        }

        public Task<APIResult> Delete(long Id)
        {
            var result = new APIResult();
            return Task.Run(() =>
            {
                var entity = _Context.Set<T>().Find(Id);
                if (entity != null)
                    _Context.Set<T>().Remove(entity);
                else
                {
                    result.Code = ErrorCode.QueryNull;
                    result.Message = "未查询到相关实体数据";
                    return result;
                }

                if (_Context.SaveChanges() >= 0)
                {
                    result.Code = ErrorCode.Success;
                    result.Message = $"删除{_OperateName}成功";
                }
                else
                {
                    result.Code = ErrorCode.ServiceError;
                    result.Message = $"删除{_OperateName}失败";
                    DefaultLogFactory.Instance.Message_Loger.Error(new { title = $"删除{_OperateName}失败", param = Id, response = result });
                }
                return result;
            });
        }
    }
}
